<!DOCTYPE html>
<html>
<head>
    <meta name="layout" content="main"/>
    <g:set var="entityName" value="${message(code: 'account.label', default: 'account')}"/>
    <title>地图绘制</title>
    <link rel="stylesheet" href="/assets/angular/tree/angular-ui-tree.min.css" />
    <style>
    %{--设置点击侧边栏如果大于当前屏幕高度则地图会变形--}%
    #wrapper{
        min-height: 0!important;
    }
    /*::-webkit-scrollbar{*/
    /*background: rgb(255,255,255) !important;*/
    /*}*/
    /*::-webkit-scrollbar-button    {*/
    /*background-color:#FF7677;*/
    /*}*/
    body, html{
        width: 100%;height: 100%;overflow: hidden;margin:0;font-family:"微软雅黑";
    }
    #content{
        width: 100%;
        top: 50px;
        bottom: 100px;
        position: absolute;
    }
    #allmap{
        width: 100%;
        height:100%;
    }
    #allmap label{max-width:none;}
    #left{
        width: 60%;
        height:100%;
        float: left;
        position: relative;
    }
    #right{
        width: 40%;
        height:100%;
        float: left;
        position: relative;
    }
    .activeAccount{
        background-color: #2479B4;
        color: white;
    }
    .panel-body .select2-choice{
        height: 28px !important;
    }
    .fixed-navbar #wrapper{
        height:100%;
    }
    .citylist_popup_main .city_content_top{
        height: 40px !important;
    }
    .media{
        margin: 0 !important;
    }
    .BMapLabel span{
        position: absolute;
        font-size: 30px;
        left:-13px;
        top:-15px;
    }
    #message{
        margin:0;
        padding:10px 10px;
        text-align: center;
        position: absolute;
        background: #fff;
        overflow-y: scroll;
        height:160px;
        list-style: none;
        display: none;
        opacity: .9;
        border-radius: 4px;
        color: #212121;
        cursor: pointer;
    }
    #message li:hover{
        background: #26b095;
        color:#fff;
        line-height:30px;
    }
    .allCheck{
        background-color: #2479B4;
        border-color: #2479B4;
        color: #fff;
        width: 22px;
        height: 22px;
    }
    </style>
</head>
<body class="fixed-navbar fixed-sidebar" >
<div style="width: 100%;height: 100%;overflow: hidden;position: relative;" ng-controller="precinctCtrl">
    <g:include view="map/Mapscript.gsp"/>
    <script type="text/javascript" src="/assets/map/draw/DrawingManager_min.js"></script>
    <link rel="stylesheet" href="/assets/map/draw/DrawingManager_min.css" />
    <!--加载检索信息窗口-->
    <script type="text/javascript" src="/assets/map/draw/SearchInfoWindow_min.js"></script>
    <link rel="stylesheet" href="/assets/map/draw/SearchInfoWindow_min.css" />
    <div class="small-header">
        <div class="hpanel">
            <div class="panel-body">
                <div id="hbreadcrumb" class="pull-right">
                    <ol class="hbreadcrumb breadcrumb">
                        <li>CINDATA PLS</li>
                        <li class="active">
                            <span>地图绘制</span>
                        </li>
                    </ol>
                </div>
                <h2 class="font-light m-b-xs">
                    地图绘制
                </h2>
            </div>
        </div>
    </div>

    <div id="content">
        <div style="width:100%;height:100%;position:relative;">
            <div id="left" >
                <div id="allmap"></div>
            </div>
            <div id="right" >
                <div class="hpanel" style="height: 100%;position: relative;">
                    <ul class="nav nav-tabs">
                        <li ng-repeat="pt in precinctTypeArr" ng-class="{'active':isCurPrecinctType(pt)}"><a ng-click="setCurPrecinctType(pt)" >{{pt.name}}</a></li>
                    </ul>
                    <div class="tab-content" style="width:100%;position: absolute;top: 40px;bottom: 0px;">
                        <div ng-repeat="pt in precinctTypeArr" id="{pt.code}" class="tab-pane" ng-class="{'active':isCurPrecinctType(pt)}" style="height: 100%;">
                            <div class="panel-body" style="height: 100%;">
                                <strong>机构树，当前选择机构：{{pt.source.name}}</strong>
                                <div style="position: absolute;top: 35px;left: 20px;right: 20px;bottom: 20px;">
                                    <div style="float: left;width: 50%;height: 100%;overflow-y:auto;">
                                        <div ui-tree data-drag-enabled="false" ng-show="pt.sourceArr.length>0">
                                            <ol ui-tree-nodes ng-model="pt.sourceArr">
                                                <li ng-repeat="node in pt.sourceArr" ui-tree-node  ng-include="'nodes_renderer.html'">
                                                </li>
                                            </ol>
                                        </div>
                                    </div>
                                    <div style="float: left;width: 50%;height: 100%;overflow-y:auto;">
                                        <div ui-tree data-drag-enabled="false" ng-show="pt.customRegionArr.length>0">
                                            <ol ui-tree-nodes ng-model="pt.customRegionArr" >
                                                <li ng-repeat="ocr in pt.customRegionArr" ui-tree-node >
                                                    <div ui-tree-handle class="tree-node tree-node-content" style="border-style: solid;" ng-class="{'activeAccount':isCurCustomRegion(ocr)}" ng-click="setCurCustomRegion(ocr)" >
                                                        {{ocr.name}}
                                                        <a class="pull-right btn btn-danger btn-xs" ng-click="delete(ocr)"><span class="glyphicon glyphicon-remove"></span></a>
                                                    </div>
                                                </li>
                                            </ol>
                                        </div>
                                    </div>
                                    <div style="clear: both;"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <g:include view="precinct/function.gsp"/>
        </div>

    </div>
</div>
<script type="text/ng-template" id="nodes_renderer.html">
    <div ui-tree-handle class="tree-node tree-node-content" style="border-style: solid;" ng-class="{'activeAccount':isCurSource(node)}" ng-click="setCurSource(node)">
        <a class="btn btn-xs allCheck" ng-if="node.children && node.children.length > 0" data-nodrag="" ng-click="toggle(this)">
            <span class="glyphicon glyphicon-chevron-down" ng-class="{'glyphicon-chevron-right': collapsed,'glyphicon-chevron-down': !collapsed}" style="right: 2.5px; color: #fff;">
            </span>
        </a>
        {{node.name}}
    </div>
    <ol ui-tree-nodes="" ng-model="node.children" ng-class="{hidden: collapsed}" >
        <li ng-repeat="node in node.children" ui-tree-node ng-include="'nodes_renderer.html'">
        </li>
    </ol>
</script>

<script type="text/ng-template" id="precinct_form.html">
    <div class="color-line"></div>
    <div class="modal-header">
        <h4 class="modal-title"><span>添加区域</span><small style="font-size: 14px" class="font-bold"> (注：<span style="color: red">*</span> 为必填)</small></h4>
    </div>
    <div class="form-horizontal" name="myForm">
        <div class="modal-body form-horizontal">
            <div class="form-group">
                <label class="col-md-2 control-label is-required">区域名称</label>
                <div class="col-md-10">
                    <input class="form-control" type="text"  ng-model="data.name"/>
                </div>
            </div>
            <div class="form-group">
                <label class="col-md-2 control-label is-required">所属机构</label>
                <div class="col-md-10">
                    <input class="form-control" type="text"  ng-model="data.sourceName" ng-disabled="true" />
                </div>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" ng-click="ok()">确定</button>
            <button type="button" class="btn btn-primary" ng-click="cancel()">取消</button>
        </div>
    </div>
</script>



<g:javascript>
    window.app.controller("precinctCtrl",function($scope,$timeout,$uibModal){
        $scope.map = null;
        $scope.local = null;
        $scope.overlays = [];
        //地图
        $scope.inputData = {
            currentMap:"AroundAccount",
            keyword: "",
            city:"-1"
        };
        //地图数据
        $scope.cityArr = [];
        $scope.city = null;
        $scope.precinctTypeArr = [
            {
                name: "周边网点" ,
                code: "AroundAccount" ,
                value: "AroundAccount",
                reqUrl: "/precinct/mapAccountData",
                class: 'com.cindata.Account',
                sourceArr: [],
                source: null,
                customRegionArr: []
            },
            {
                name: "开发商楼盘" ,
                code: "Developer" ,
                value: "Developer",
                reqUrl: "/precinct/mapDeveloperData",
                class: 'com.cindata.Developer',
                sourceArr: [],
                source: null,
                customRegionArr: []
            }
        ];
        $scope.precinctType = $scope.precinctTypeArr[0];
        //区块类型数组
        // 初始化地图
        $scope.initMap = function(){
            //加载百度地图底图
            $scope.map = new BMap.Map('allmap');
            //设置中心点坐标
            $scope.map.centerAndZoom(new BMap.Point(116.404, 39.915),13);
            $scope.map.enableScrollWheelZoom(true);
            $scope.local = new BMap.LocalSearch($scope.map, {
                renderOptions: {
                    map: $scope.map,
                    panel: "searchResult",
                    autoViewport:true,
                    selectFirstResult: true
                },
                onMarkersSet:function(pois){
                },
                onInfoHtmlSet:function(poi){
                    $scope.map.centerAndZoom(poi.point,18);
                },
                // onSearchComplete: function(results){
                //     // 判断状态是否正确
                //     if ($scope.local.getStatus() == BMAP_STATUS_SUCCESS){
                //         var s = [];
                //         for (var i = 0; i < results.getCurrentNumPois(); i ++){
                //             s.push(results.getPoi(i).title + ", " + results.getPoi(i).address);
                //         }
                //     }
                // },
                pageCapacity: 5
            });
        };
        // //初始化地图图层
        $scope.initOverlay = function(){
            $scope.map.clearOverlays();
            //清除所有地图覆盖物
        };
        $scope.keySearch = function($event){
            if($event.keyCode === 13){
                $scope.search();
            }
        };
        //切换城市地图事件
        $scope.search = function(){
            //清空搜索
            var zoneNumber = $scope.inputData.city;
            var cityName = $("#city").find("option:selected").text();
            if((!zoneNumber || zoneNumber=="-1") && (!cityName || cityName=="请选择城市")){
                return;
            }
            $scope.map.centerAndZoom(cityName,13);
            $scope.searchData();
        };
        //参数改变事件
        $scope.searchData = function(){
            //搜索条件改变事件
            if($scope.inputData.keyword.trim()==""){
                return;
            }
            var myKeys = $scope.inputData.keyword;
            $scope.local.search(myKeys);
        };
        $scope.initDraw = function (){
            var styleOptions = {
                strokeColor:"red",    //边线颜色。
                fillColor:"red",      //填充颜色。当参数为空时，圆形将没有填充效果。
                strokeWeight: 3,       //边线的宽度，以像素为单位。
                strokeOpacity: 0.8,	   //边线透明度，取值范围0 - 1。
                fillOpacity: 0.6,      //填充的透明度，取值范围0 - 1。
                strokeStyle: 'solid' //边线的样式，solid或dashed。
            };
            //实例化鼠标绘制工具
            var drawingManager = new BMapLib.DrawingManager($scope.map, {
                isOpen: false, //是否开启绘制模式
                enableDrawingTool: true, //是否显示工具栏
                drawingToolOptions: {
                    anchor: BMAP_ANCHOR_TOP_RIGHT, //位置
                    offset: new BMap.Size(5, 5), //偏离值
                    drawingModes : [
                        // BMAP_DRAWING_CIRCLE,
                        // BMAP_DRAWING_RECTANGLE,
                        BMAP_DRAWING_POLYGON
                    ]
                },
                circleOptions: styleOptions, //圆的样式
                polylineOptions: styleOptions, //线的样式
                polygonOptions: styleOptions, //多边形的样式
                rectangleOptions: styleOptions //矩形的样式
            });
            //添加鼠标绘制工具监听事件，用于获取绘制结果
            drawingManager.addEventListener('overlaycomplete', function(e){
                $scope.overlays.push(e.overlay);
                $scope.afterDraw(e.overlay);
            });
        };
        $scope.clearDraw = function(){
            for(var i = 0; i < $scope.overlays.length; i++){
                $scope.map.removeOverlay($scope.overlays[i]);
            }
            $scope.overlays.length = 0;
        };
        $scope.initCtrl = function () {
            $("#city").change(function(){
                $scope.inputData.zoneNumber = $(this).val();
                $scope.search();
            });
        };
        $scope.initData = function(){
            $.ajax({
                type: "get",
                url: "/precinct/getInitData",
                data: {},
                success:function (data) {
                    if(!data.success){
                        swal('错误',data.error,'error');
                        return
                    }
                    $timeout(function(){
                        $scope.precinctTypeArr[0].sourceArr = data.accountArr;
                        $scope.precinctTypeArr[1].sourceArr = data.developerArr;
                    },0);

                }
            })
        };
        $scope.toggle = function (scope) {
            scope.toggle();
        };
        $scope.getCustomRegionData = function(params){
            $.ajax({
                type: "get",
                url: "/precinct/getCustomRegionData",
                data: params,
                success:function (data) {
                    if(!data.success){
                        swal('错误',data.error,'error');
                        return
                    }
                    $timeout(function(){
                        $scope.precinctType.customRegionArr = data.customRegionArr;
                    },0);
                    $scope.map.clearOverlays();
                }
            })
        };
        $scope.setCurSource = function(curSource){
            $scope.precinctType.source = curSource;
            $scope.getCustomRegionData({
                sourceId: $scope.precinctType.source.id,
                sourceClass: $scope.precinctType.class
            });
        };
        $scope.isCurSource = function(tempSource){
            return ($scope.precinctType.source == tempSource)
        };
        $scope.setCurCustomRegion = function(curCustomRegion){
            $scope.precinctType.customRegion = curCustomRegion;
            $scope.map.clearOverlays();
            $scope.reDrawCustomRegion(curCustomRegion);
        };
        $scope.isCurCustomRegion = function(tempCustomRegion){
            return ($scope.precinctType.customRegion == tempCustomRegion)
        };
        $scope.setCurPrecinctType = function(curPrecinctType){
            $scope.precinctType = curPrecinctType;
        };
        $scope.isCurPrecinctType = function(tempPrecinctType){
            return ($scope.precinctType == tempPrecinctType)
        };
        $scope.afterDraw = function(overlay){
            if($scope.precinctType.source == null){
                swal('错误','必须先选择一个所属机构',"error");
                $timeout(function(){
                    $scope.clearDraw();
                },0);
                return false;
            }
            $scope.openForm(overlay);
            return true;
        };
        //重新绘制自定义区域
        $scope.reDrawCustomRegion = function(customRegion){
            var pathStrArr = customRegion.coordinates;
            var pathArr = pathStrArr.split(";");
            pathArr = pathArr.map(function(item){
                var tempPoint = item.split(",");
                return new BMap.Point(tempPoint[0], tempPoint[1]);
            });
            var centerPoint = new BMap.Point(customRegion.x,customRegion.y);
            var region = new BMap.Polygon(pathArr, {strokeColor:"blue", strokeWeight:2, strokeOpacity:0.5});
            var regionLabel = new BMap.Label(customRegion.name,{position: centerPoint,offset   : new BMap.Size(-30,-10) });
            regionLabel.setStyle({
                color: "red",
                fontSize : "12px",
                height : "20px",
                lineHeight : "20px"
            });
            // customRegion.setPath(pathArr);
            $scope.map.addOverlay(region);
            $scope.map.addOverlay(regionLabel);
            $scope.map.centerAndZoom(centerPoint,18);
        };
        $scope.openForm = function(overlay){
            var modalInstance = $uibModal.open({
                animation: true,
                templateUrl: 'precinct_form.html',
                controller: 'precinctFormCtrl',
                size: '',
                resolve: {
                    params: function () {
                       return {
                           source: $scope.precinctType.source
                       };
                    }
                }
            });
            modalInstance.result.then(function (params) {
                var pathArr = overlay.getPath();
                pathArr = pathArr.map(function(item){
                    return (item.lng+","+item.lat);
                });
                params.path = pathArr.join(";");
                params.type = $scope.precinctType.code;
                params.class = $scope.precinctType.class;
                var centerPoint = overlay.getBounds().getCenter();
                params.x = centerPoint.lng;
                params.y = centerPoint.lat;
                $scope.save(params);
            }, function () {
                $timeout(function(){
                    $scope.clearDraw();
                },0);
                console.info('Modal dismissed at: ' + new Date());
            });
        };
        $scope.save = function(params){
            $.ajax({
                type: "post",
                url: "/precinct/saveData",
                data: params,
                success:function (data) {
                    if(!data.success){
                        swal('错误',data.error,'error');
                        return
                    }
                    $timeout(function(){
                        $scope.precinctType.customRegionArr.push(data.customRegion);
                    },0);
                    swal('成功',"增加区域"+data.customRegion.name+"成功",'success');
                }
            });
        };
        $scope.delete = function(customRegion){
            swalConfirm("确定删除吗？",("将删除区域"+customRegion.name+"！"),function(){
                $scope.deleteAction(customRegion);
            });
        };
        $scope.deleteAction = function(customRegion){
            $.ajax({
                type: "post",
                url: "/precinct/deleteData",
                data: {
                    id: customRegion.id
                },
                success:function (data) {
                    if(!data.success){
                        swal('错误',data.error,'error');
                        return
                    }
                    $timeout(function(){
                        var tempIndex = $scope.precinctType.customRegionArr.indexOf(customRegion);
                        $scope.precinctType.customRegionArr.splice(tempIndex,1);
                    },0);
                }
            });
        };
        $scope.init = function(){
            $scope.initData();
            $scope.initMap();
            $scope.initDraw();
            $scope.initCtrl();
        };
        $scope.init();
    });
    window.app.controller("precinctFormCtrl",function($scope,$uibModalInstance,params){
        $scope.source = null;
        $scope.data = {
            id:"",
            name:"",
            sourceId:"",
            sourceName:""
        };
        $scope.readParams = function(){
            if(params.id){
                $scope.data = params;
            }
            else{
                $scope.source = params.source;
            }
            $scope.data.sourceId = $scope.source.id;
            $scope.data.sourceName = $scope.source.name;
        };
        $scope.ok = function () {
            if($scope.data.name == null || $scope.data.name == ""){
                swal('错误',"区域名称必填",'error');
                return
            }
            $uibModalInstance.close($scope.data);
        };
        $scope.cancel = function () {
            $uibModalInstance.dismiss('cancel');
        };
        $scope.readParams();
    });
</g:javascript>
</body>
</html>
